package com.huidu.bitrade.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huidu.bitrade.constant.MemberLevelEnum;
import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.mapper.HdzImportMapper;
import com.huidu.bitrade.mapper.MemberImportMapper;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.util.GeneratorUtil;
import com.huidu.bitrade.util.IdWorkByTwitter;
import com.huidu.bitrade.util.Md5;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class MemberImportServiceImpl extends ServiceImpl<MemberImportMapper, MemberImport> implements MemberImportService {

    private final MemberService memberService;
    private final IdWorkByTwitter idWorkByTwitter;
    private final MemberWalletService memberWalletService;

    @Override
    @Transactional
    public void memberImport(MemberImport memberImport,List<Coin> coins) throws Exception {
        //查询用户是否存在
        Member member = memberService.findByPhone(memberImport.getMobilePhone());
        if(Objects.isNull(member)){//创建账号
            member = createMember(memberImport.getMobilePhone(),coins);
        }else{
            //查询是否有钱包，没有则创建
            List<MemberWallet> walletList = memberWalletService.findAllByMemberId(member.getId());
            if(CollectionUtils.isEmpty(walletList)){
                setWallet(coins,member.getId());
            }
        }
        //修改用户余额
        BigDecimal fee = BigDecimal.valueOf(0.92);
        if(memberImport.getHdz().compareTo(BigDecimal.ZERO)>0){
            addBalance(memberImport.getHdz().multiply(fee),member.getId(),"HDZ");
        }
        if(memberImport.getHdc().compareTo(BigDecimal.ZERO)>0){
            addBalance(memberImport.getHdc().multiply(fee),member.getId(),"HDC");
        }
        if(memberImport.getCnhd().compareTo(BigDecimal.ZERO)>0){
            addBalance(memberImport.getCnhd().multiply(fee),member.getId(),"CNHD");
        }
        //修改此条记录状态为已导入
        memberImport.setStatus(1);
        updateById(memberImport);
    }

    /**
     * 转入到余额
     */
    private void addBalance(BigDecimal amount,Long memberId,String unit){
        MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(unit,memberId);
        log.info("=============用户钱包==========={}",memberWallet);
        Assert.notNull(memberWallet,"未找到用户钱包");
        int save = memberWalletService.increaseBalance(memberWallet.getId(),amount);
        if(save<1){
            log.info("=========修改用户hdz钱包余额异常==========={}",memberId);
            throw new IllegalArgumentException("修改用户钱包余额异常");
        }
    }

    /**
     * 创建新用户
     * @param phone
     * @param coins
     * @return
     * @throws Exception
     */
    @Override
    public Member createMember(String phone,List<Coin> coins) throws Exception {
        Member member = new Member();
        member.setSuperPartner("0");
        member.setMemberLevel(MemberLevelEnum.GENERAL);
        Location location = new Location();
        location.setCountry("中国");
        Country country = new Country();
        country.setZhName("中国");
        member.setCountry(country);
        member.setLocation(location);
        member.setType(1);
        member.setUsername(phone);
        //不可重复随机数
        String loginNo = String.valueOf(idWorkByTwitter.nextId());
        //盐
        String credentialsSalt = ByteSource.Util.bytes(loginNo).toHex();
        member.setPassword(Md5.md5Digest(RandomUtil.randomNumbers(6)+credentialsSalt).toLowerCase());
        member.setMobilePhone(phone);
        member.setSalt(credentialsSalt);
        member.setAvatar("https://bizzan6.oss-accelerate.aliyuncs.com/defaultavatar.png"); // 默认用户头像
        Member member1 = memberService.save(member);
        if (member1 != null) {
            // Member为@entity注解类，与数据库直接映射，因此，此处setPromotionCode会直接同步到数据库
            member1.setPromotionCode(GeneratorUtil.getPromotionCode(member1.getId()));
            setWallet(coins,member1.getId());
        }
        return member1;
    }

    @Override
    public void setWallet(List<Coin> coins,Long memberId){
        // 增加钱包记录
        for(Coin coin:coins) {
            MemberWallet wallet = new MemberWallet();
            wallet.setCoin(coin);
            wallet.setMemberId(memberId);
            wallet.setBalance(new BigDecimal(0));
            wallet.setFrozenBalance(new BigDecimal(0));
            wallet.setSystemFrozen(new BigDecimal(0));
            wallet.setAddress("");
            //保存
            memberWalletService.save(wallet);
        }
    }
}
